#!/usr/bin/env python

__author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"

class WeeklyChart (object):

	def __init__(self,
				 user = None,
				 group = None,
				 start = None,
				 end = None):
		kind = name = None
		if user:
			kind, name = 'user', user
		elif group:
			kind, name = 'group', group
		else:
			raise AudioscrobblerError("either user or group has to be provided")

		if start and end:
			if type(start) != datetime:
				self.start = datetime.fromtimestamp(start)
				self.end = datetime.fromtimestamp(end)
			else:
				self.start = start
				self.end = end
			parameters = {
				'from': int(time.mktime(self.start.timetuple())),
				'to': int(time.mktime(self.end.timetuple()))
			}
		else:
			self.start = None
			self.end = None
			parameters = {}

		if type(self) != WeeklyChart:
			url = "http://ws.audioscrobbler.com/1.0/%s/%s/%s.xml" %\
				(kind, name, str(self.__class__).split('.')[-1][:-2].lower())

			xml = Webservice()._FetchUrl(url, parameters)
			self.data = Xml2Dict(ElementTree.XML(xml))

class WeeklyArtistChart (WeeklyChart):

	def __init__(self,
				 user = None,
				 group = None,
				 start = None,
				 end = None):
		WeeklyChart.__init__(self, user, group, start, end)

		artists = []
		if 'playcount' in self.data['artist'][0]:
			self.playcount = 0
		if 'reach' in self.data['artist'][0]:
			self.reach = 0
			
		if 'artist' in self.data:
			for artistData in self.data['artist']:
				artist = Artist(
					name = artistData['name'],
					url = artistData['url'],
				)
				if 'mbid' in artistData:
					artist.mbid = artistData['mbid']
				artist.chartposition = int(artistData['chartposition'])
				if 'playcount' in artistData:
					artist.playcount = int(artistData['playcount'])
					self.playcount += artist.playcount
				if 'reach' in artistData:
					artist.reach = int(artistData['reach'])
					self.reach += artist.reach
				artists.append(artist)

		self.start = datetime.fromtimestamp(int(self.data['@from']))
		self.end = datetime.fromtimestamp(int(self.data['@to']))
		self.artists = artists
		del self.data

class WeeklyAlbumChart (WeeklyChart):

	def __init__(self,
				 user = None,
				 group = None,
				 start = None,
				 end = None):
		WeeklyChart.__init__(self, user, group, start, end)

		albums = []
		if 'playcount' in self.data['album'][0]:
			self.playcount = 0
		if 'reach' in self.data['album'][0]:
			self.reach = 0
		
		if 'album' in self.data:
			for albumData in self.data['album']:
				album = Album(
					name = albumData['name'],
					url = albumData['url'],
				)
				albumArtist = Artist(name = albumData['artist']['text'])
				if '@mbid' in albumData['artist']:
					albumArtist.mbid = albumData['artist']['@mbid']
				album.artist = albumArtist

				if 'mbid' in albumData:
					album.mbid = albumData['mbid']
				album.chartposition = int(albumData['chartposition'])
				if 'playcount' in albumData:
					album.playcount = int(albumData['playcount'])
					self.playcount += album.playcount
				if 'reach' in albumData:
					album.reach = int(albumData['reach'])
					self.reach += album.reach
				albums.append(album)

		self.start = datetime.fromtimestamp(int(self.data['@from']))
		self.end = datetime.fromtimestamp(int(self.data['@to']))
		self.albums = albums
		del self.data

class WeeklyTrackChart (WeeklyChart):

	def __init__(self,
				 user = None,
				 group = None,
				 start = None,
				 end = None):
		WeeklyChart.__init__(self, user, group, start, end)

		tracks = []
		if 'playcount' in self.data['track'][0]:
			self.playcount = 0
		if 'reach' in self.data['track'][0]:
			self.reach = 0

		if 'track' in self.data:
			for trackData in self.data['track']:
				track = Track(
					name = trackData['name'],
					url = trackData['url'],
				)
				trackArtist = Artist(name = trackData['artist']['text'])
				if '@mbid' in trackData['artist']:
					trackArtist.mbid = trackData['artist']['@mbid']
				track.artist = trackArtist

				if 'mbid' in trackData:
					track.mbid = trackData['mbid']
				track.chartposition = int(trackData['chartposition'])
				if 'playcount' in trackData:
					track.playcount = int(trackData['playcount'])
					self.playcount += track.playcount
				if 'reach' in trackData:
					track.reach = int(trackData['reach'])
					self.reach += track.reach
				tracks.append(track)

		self.start = datetime.fromtimestamp(int(self.data['@from']))
		self.end = datetime.fromtimestamp(int(self.data['@to']))
		self.tracks = tracks
		del self.data
		
import cElementTree as ElementTree
import time
from datetime import datetime

from album import Album
from artist import Artist
from webservice import Webservice
from track import Track
from xml2dict import Xml2Dict
from error import AudioscrobblerError